package gbench.appdemo.mall.appitf.media;

import static gbench.common.matlib.MatlibCanvas.println;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *  媒体文件
 * @author gbench
 *
 */
@RequestMapping("media")
@RestController
public class MediaController {
    
    /**
     * 通过produces 告知浏览器我要返回的媒体类型
     * http://localhost:8082/mall/media/imagefile?file=D:/sliced/tmp/avatar.jpg
     * @param file 文件名称
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/imagefile", produces = { 
            MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_GIF_VALUE,
            MediaType.IMAGE_PNG_VALUE })
    public BufferedImage imagefile(final String file) throws IOException {
        return ImageIO.read(new FileInputStream(new File(file)));
    }

    /**
     * 二进制文件
     * http://localhost:8082/mall/media/binaryfile?file=D:/sliced/tmp/avatar.jpg
     * @param response 
     * @param file 文件路径
     * @throws IOException
     */
    @RequestMapping(value = "/binaryfile")
    public void binaryfile(final HttpServletResponse response, final String file) throws IOException {
        File binaryfile = new File(file);
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(binaryfile));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    
    /**
     * 流文件读取
     * 
     * http://localhost:8082/mall/media/streamfile?file=D:/sliced/ws/medias/avatar.jpg
     * http://localhost:8082/mall/media/streamfile?file=D:/sliced/ws/medias/wallstreet_wolf_2.mp4
     * http://localhost:8082/mall/media/streamfile?file=D:/sliced/ws/medias/music1.mp3
     * 
     * @param request 请求对象
     * @param response 回复对象
     * @param file 流媒体文件名称
     */
    @RequestMapping("/streamfile")
    public void streamfile(final HttpServletRequest request, final HttpServletResponse response, final String file) {

        final String database = FTP_SERVER_URL + FTP_SERVER_MEDIA_HOME;// 音频文件所在的文件夹路径
        // 文件目录（偷懒没有改变量，名称，此处和FTP没关系，就是文件的绝对路径）
        // 也就是 File mediafile = new File("C:\Users\Administrator\AppData\Local\Temp\a.mp3");
        final File mediafile = new File(database + file);
        if (!mediafile.exists()) {
            println(database + "不存在 文件名为：" + file + "的媒体文件！");
        }
        String range = request.getHeader("Range");
        // 开始下载位置
        long startByte = 0;
        // 结束下载位置
        long endByte = mediafile.length() - 1;
        // 有range的话
        if (range != null && range.contains("bytes=") && range.contains("-")) {
            range = range.substring(range.lastIndexOf("=") + 1).trim();
            String ranges[] = range.split("-");
            try {
                // 判断range的类型
                if (ranges.length == 1) {
                    // 类型一：bytes=-2343
                    if (range.startsWith("-")) {
                        endByte = Long.parseLong(ranges[0]);
                    }
                    // 类型二：bytes=2343-
                    else if (range.endsWith("-")) {
                        startByte = Long.parseLong(ranges[0]);
                    }
                }
                // 类型三：bytes=22-2343
                else if (ranges.length == 2) {
                    startByte = Long.parseLong(ranges[0]);
                    endByte = Long.parseLong(ranges[1]);
                }
            } catch (NumberFormatException e) {
                startByte = 0;
                endByte = mediafile.length() - 1;
            }
        }
        // 要下载的长度
        final long contentLength = endByte - startByte + 1;
        // 文件名
        final String fileName = mediafile.getName();
        // 文件类型
        final String contentType = request.getServletContext().getMimeType(fileName);
        // 各种响应头设置
        // 参考资料：https://www.ibm.com/developerworks/cn/java/joy-down/index.html
        // 坑爹地方一：看代码
        response.setHeader("Accept-Ranges", "bytes");
        // 坑爹地方二：http状态码要为206
        response.setStatus(206);
        response.setContentType(contentType);
        response.setHeader("Content-Type", contentType);
        // 这里文件名换你想要的，inline表示浏览器直接实用（我方便测试用的）
        // 参考资料：http://hw1287789687.iteye.com/blog/2188500
        // response.setHeader("Content-Disposition", "inline;filename=test.mp3");
        response.setHeader("Content-Length", String.valueOf(contentLength));
        // 坑爹地方三：Content-Range，格式为
        // [要下载的开始位置]-[结束位置]/[文件总大小]
        response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + mediafile.length());
        BufferedOutputStream outputStream = null;
        RandomAccessFile randomAccessFile = null;
        // 已传送数据大小
        long transmitted = 0;
        try {
            randomAccessFile = new RandomAccessFile(mediafile, "r");
            outputStream = new BufferedOutputStream(response.getOutputStream());
            final byte[] buff = new byte[4096];
            int len = 0;
            randomAccessFile.seek(startByte);
            // 坑爹地方四：判断是否到了最后不足4096（buff的length）个byte这个逻辑（(transmitted + len) <=
            // contentLength）要放前面！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
            // 不然会会先读取randomAccessFile，造成后面读取位置出错，找了一天才发现问题所在
            while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
                outputStream.write(buff, 0, len);
                transmitted += len;
                // 停一下，方便测试，用的时候删了就行了
                // Thread.sleep(10);
            }
            // 处理不足buff.length部分
            if (transmitted < contentLength) {
                len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
                outputStream.write(buff, 0, len);
                transmitted += len;
            }
            outputStream.flush();
            response.flushBuffer();
            randomAccessFile.close();
            println("下载完毕：" + startByte + "-" + endByte + "：" + transmitted);
        } catch (ClientAbortException e) {
            println(e);
            println("用户停止下载：" + startByte + "-" + endByte + "：" + transmitted);
            // 捕获此异常表示拥护停止下载
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                } // if
            } catch (IOException e) {
                e.printStackTrace();
            }// try
        }// try
    } // stream
    
    final String FTP_SERVER_URL = ""; // FTP SERVER的服务器地址
    final String FTP_SERVER_MEDIA_HOME = ""; // 媒体根目录

}
